//
//  MyDepositSlipViewController.m
//  CBT
//
//  Created by Mr.Zhang on 2018/11/21.
//  Copyright © 2018 Mr.Zhang. All rights reserved.
//

#import "MyDepositSlipViewController.h"
#import "AMYestodayListVC.h"

#import "MyDepositViewModel.h"
#import "MyDepositCell.h"

@interface MyDepositSlipViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) NoDataView *noNetWorkView;
@property (nonatomic, strong) NoDataView *noDataView;
@property (nonatomic, strong) MyDepositViewModel *viewModel;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, copy) NSString *page;

@end

@implementation MyDepositSlipViewController

#pragma mark - VC Life

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = kLocalizedString(@"我的收益", nil);

    self.page = @"1";
    [self.view addSubview:self.tableView];
    
    [self outPutAction];
    [self rightButton];
}

-(void)rightButton {
    UIButton * issueButton = [UIButton buttonWithType:UIButtonTypeCustom];
    issueButton.frame = CGRectMake(0, 0, 40, 24);
    issueButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [issueButton setTitle:kLocalizedString(@"收益记录", nil) forState:UIControlStateNormal];
    [issueButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [issueButton addTarget:self action:@selector(RighttouchEvent) forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *leftBarButtomItem = [[UIBarButtonItem alloc]initWithCustomView:issueButton];
    self.navigationItem.rightBarButtonItem = leftBarButtomItem;
}

- (void)RighttouchEvent {
    AMYestodayListVC *vc = [[AMYestodayListVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - OutPut

- (void)outPutAction {
    @weakify(self);
    //存单列表请求成功
    [self.viewModel.listSuccessObject subscribeNext:^(MyInvestListModel *listModel) {
        [self_weak_ stopLoading];
        if ([self_weak_.page intValue] == 1) {
            self_weak_.dataArray = [NSMutableArray array];
        }
        
        [self_weak_.noNetWorkView removeFromSuperview];
        if (listModel.investList.count == 0 && [NSArray isArrayEmpty:self_weak_.dataArray]) {
            self_weak_.tableView.mj_footer.hidden = YES;
            [self_weak_.tableView addSubview:self_weak_.noDataView];
        }
        else {
            self_weak_.tableView.mj_footer.hidden = NO;
            [self_weak_.dataArray addObjectsFromArray:listModel.investList];
            self_weak_.page = [NSString stringWithFormat:@"%d",[self_weak_.page intValue] + 1];
        }
        if ([self_weak_.page intValue] > [listModel.totalPage intValue]) {
            [self_weak_.tableView.mj_header endRefreshing];
            [self_weak_.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        else {
            [self_weak_.tableView.mj_header endRefreshing];
            [self_weak_.tableView.mj_footer endRefreshing];
        }
        [self_weak_.tableView reloadData];
    }];
    
    //存单列表请求失败
    [self.viewModel.listFailureObject subscribeNext:^(id x) {
        [HFStatusView showFailureMessage:kLocalizedString(@"网络异常，请稍后重试", nil)];
        [self_weak_ stopLoading];
        [self_weak_.noDataView removeFromSuperview];
        if (self_weak_.dataArray.count == 0) {
            self_weak_.tableView.mj_footer.hidden = YES;
            [self_weak_.view addSubview:self_weak_.noNetWorkView];
        }
        [self_weak_.tableView.mj_header endRefreshing];
        [self_weak_.tableView.mj_footer endRefreshing];
    }];

    //获取本金获取存单状态请求成功
    [self.viewModel.investStateSuccess subscribeNext:^(id x) {
        [self_weak_ stopLoading];
        if ([x[@"code"]intValue] == 1) {
            [HFAlert showHFNewAlertInViewController:self_weak_ title:kLocalizedString(@"是否提取本金?",nil) message:nil  cancleButtonTitle:kLocalizedString(@"取消",nil) okButtonTitle:kLocalizedString(@"确认",nil) cancelClickHandle:nil okClickHandle:^{
                [self_weak_.viewModel takedrawCapitalOrIncomeWithInvestId:((MyInvestListItemModel *)self_weak_.dataArray[[x[@"indexPath"]integerValue]]).ID];
            }];
        }
        else {
            [HFAlert showHFAlertInViewController:self_weak_ title:x[@"msg"] message:nil cancleButtonTitle:kLocalizedString(@"取消",nil) okButtonTitle:kLocalizedString(@"确认",nil) cancelClickHandle:nil okClickHandle:^{
                [self_weak_ startClearBgColorLoading];
                [self_weak_.viewModel takedrawCapitalOrIncomeWithInvestId:((MyInvestListItemModel *)self_weak_.dataArray[[x[@"indexPath"]integerValue]]).ID];
            }];
        }
    }];
    
    //获取本金获取存单状态请求失败
    [self.viewModel.investStateFailure subscribeNext:^(id x) {
        [self_weak_ stopLoading];
    }];
    
    //提取本金成功
    [self.viewModel.takeOriginalSuccessObject subscribeNext:^(NSIndexPath *indexPath) {
        [self_weak_ stopLoading];
        self_weak_.page = @"1";
        [self_weak_.viewModel exchangeDataWithPage:self_weak_.page];
    }];
    
    //提取本金失败
    [self.viewModel.takeOriginalFailureObject subscribeNext:^(id x) {
        [self_weak_ stopLoading];
        NSLog(@"提取本金失败");
    }];
    
    //续投成功
    [self.viewModel.continueSuccessObject subscribeNext:^(id x) {
        [self_weak_ stopLoading];
        NSLog(@"续投成功");
        self_weak_.page = @"1";
        [self_weak_.viewModel exchangeDataWithPage:self_weak_.page];
    }];
    
    //续投失败
    [self.viewModel.continueFailureObject subscribeNext:^(id x) {
        [self_weak_ stopLoading];
        NSLog(@"续投失败");
    }];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyDepositCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    cell.indexPath = indexPath.row;
    cell.model = self.dataArray[indexPath.row];
    __weak MyDepositSlipViewController *weakSelf = self;
    [cell setMyDepositBlock:^(NSInteger indexPath, NSInteger type){
        [weakSelf startClearBgColorLoading];
        if (type == 0) {
            [weakSelf.viewModel takedrawCapitalOrIncomeWithUserId:[CBTLocalUserManager sharedInstance].userId investId:((MyInvestListItemModel *)weakSelf.dataArray[indexPath]).ID indexPath:indexPath];
        }
        else {
            [weakSelf.viewModel userContinueInvestWithInvestId:((MyInvestListItemModel *)weakSelf.dataArray[indexPath]).ID];
        }
    }];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 210;
}

#pragma mark - Lazy

- (NoDataView *)noDataView
{
    if (!_noDataView) {
        _noDataView = [[NoDataView alloc]initWithFrame:self.view.bounds type:(ShowType_NoData) clickBlock:^{}];
    }
    return _noDataView;
}

- (NoDataView *)noNetWorkView
{
    if (!_noNetWorkView) {
        @weakify(self);
        _noNetWorkView = [[NoDataView alloc]initWithFrame:self.view.bounds type:(ShowType_NoNetWork) clickBlock:^{
            [self_weak_ startClearBgColorLoading];
            [self_weak_.noDataView removeFromSuperview];
            [self_weak_.noNetWorkView removeFromSuperview];
            self_weak_.page = @"1";
            [self_weak_.viewModel exchangeDataWithPage:self_weak_.page];
        }];
    }
    return _noNetWorkView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (MyDepositViewModel *)viewModel
{
    if (!_viewModel) {
        _viewModel = [[MyDepositViewModel alloc]init];
    }
    return _viewModel;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenNarrowSide, ScreenWideSide - self.tabBarController.tabBar.bounds.size.height - (HFIphoneX ? HFIPhoneXSafeAreaPotraitBottom : 15)) style:(UITableViewStylePlain)];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.contentInset = UIEdgeInsetsMake(5, 0, 0, 0);
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellEditingStyleNone;
        
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        if (@available(iOS 11.0, *)){
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }else{
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _tableView.estimatedRowHeight           = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        
        [_tableView registerClass:[MyDepositCell class] forCellReuseIdentifier:@"Cell"];
        
        __weak MyDepositSlipViewController *weakSelf = self;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            weakSelf.page = @"1";
            [weakSelf.viewModel exchangeDataWithPage:weakSelf.page];
        }];
        
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            [weakSelf.viewModel exchangeDataWithPage:weakSelf.page];
        }];
        
        _tableView.mj_footer.hidden = YES;
        
        [_tableView.mj_header beginRefreshing];
    }
    return _tableView;
}

@end
